package com.onenine.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.manager.OssManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.onenine.app.R;
import com.onenine.app.adapter.ImageAddAdapter;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.event.SelectedLabelEvent;
import com.onenine.app.event.SingleInputEvent;
import com.onenine.app.listener.LastItemUnDragAndSwipeCallback;
import com.onenine.app.model.LabelItem;
import com.onenine.app.request.EditInfoRequest;
import com.onenine.app.response.UserInfoResponse;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.GlideUtils;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.SingleSelectView;
import com.onenine.app.view.TransitionViewHelper;
import com.onenine.app.view.city.ProvincePickPopWin;
import com.onenine.app.view.date.DatePickerPopWin;
import com.onenine.app.view.popwin.MediaPopWindow;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.utils.Toasty;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.KeyboardUtils;
import com.onenine.common.util.ScreenUtils;
import com.onenine.common.util.SizeUtils;
import com.onenine.common.util.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 编辑资料
 */
public class EditInfoActivity extends UploadImageActivity implements View.OnClickListener
        , BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    private static final int IMAGE_COLUMN = 3;
    private UserInfoResponse mInfoResponse;
    private RecyclerView mRecyclerView;
    private ImageAddAdapter mImageAdapter;
    private TextView mAlbumHint;
    private SingleSelectView mNameSV, mBirthdaySV, mHomeSV, mSignSV;
    private SingleSelectView mLabelSL, mObjectSL, mHobbySL;
    private ImageView mIvHeadPic;

    public static void launchActivity(Context context) {
        Intent intent = new Intent(context, EditInfoActivity.class);
        context.startActivity(intent);
    }

    public static void launchActivity(Context context, boolean launchLabel) {
        Intent intent = new Intent(context, EditInfoActivity.class);
        intent.putExtra("launchLabel", launchLabel);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_edit_info;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mToolbar.setCenterTitle(R.string.edit_info);
        mToolbar.setRightTitle(R.string.save);
        mToolbar.setLeftTitle(R.string.cancel);
        mToolbar.setRightTitleColor(RoleResLoader
                .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR));
        mAlbumHint = findViewById(R.id.tv_album_count_hint);
        mAlbumHint.setText(getString(R.string.album_action_count_hint, 0));
        mRecyclerView = findViewById(R.id.rv_grid);
        mNameSV = findViewById(R.id.ssv_name);
        mNameSV.setLeftTextColor(R.color.c666);
        mBirthdaySV = findViewById(R.id.ssv_birthday);
        mBirthdaySV.setLeftTextColor(R.color.c666);
        mIvHeadPic = findViewById(R.id.iv_headpic);
        mHomeSV = findViewById(R.id.ssv_hometown);
        mHomeSV.setLeftTextColor(R.color.c666);
        mSignSV = findViewById(R.id.ssv_sign);
        mSignSV.setLeftTextColor(R.color.c666);
        mLabelSL = findViewById(R.id.ssl_my_label);
        mLabelSL.setLeftTextColor(R.color.c666);
        mObjectSL = findViewById(R.id.ssl_my_object);
        mObjectSL.setLeftTextColor(R.color.c666);
        mHobbySL = findViewById(R.id.ssl_my_hobby);
        mHobbySL.setLeftTextColor(R.color.c666);
        mImagePaths.add(IMAGE_ADD);
        mImageAdapter = new ImageAddAdapter(mImagePaths, (AppConfig.SCREEN_WIDTH - SizeUtils.dp2px(58)) / IMAGE_COLUMN);
        mImageAdapter.enableDragItem(new LastItemUnDragAndSwipeCallback(mRecyclerView, mImageAdapter).getItemTouchHelper());
        mImageAdapter.bindToRecyclerView(mRecyclerView);
        mRecyclerView.setNestedScrollingEnabled(false);
        mInfoResponse = RcUser.getInstance().getInfoResponse();
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mToolbar.setOnRightClickListener(this);
        mImageAdapter.setOnItemClickListener(this);
        mImageAdapter.setOnItemChildClickListener(this);
        mNameSV.setOnClickListener(this);
        mHomeSV.setOnClickListener(this);
        mBirthdaySV.setOnClickListener(this);
        mSignSV.setOnClickListener(this);
        mLabelSL.setOnClickListener(this);
        mObjectSL.setOnClickListener(this);
        mHobbySL.setOnClickListener(this);
        mIvHeadPic.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, IMAGE_COLUMN));
        mRecyclerView.setHasFixedSize(true);
        mNameSV.setLeftText(R.string.nick_name);
        mBirthdaySV.setLeftText(R.string.birthday);
        mHomeSV.setLeftText(R.string.hometown);
        mLabelSL.setLeftText(R.string.my_label);
        mObjectSL.setLeftText(R.string.my_object);
        mHobbySL.setLeftText(R.string.my_hobby);
        mSignSV.setLeftText(R.string.special_sign);
        mHomeSV.setRightText(mInfoResponse.getProvinceName() + " " + mInfoResponse.getCityName());
        mNameSV.setRightText(mInfoResponse.getNickName());
        GlideUtils.loadCircleAvatar(this, mIvHeadPic, mInfoResponse.getPhoto());
        showLabelData(DataType.MY_LABEL, mLabelSL
                , mInfoResponse.getMylabelIds(), mInfoResponse.getMylabelNames());
        showLabelData(DataType.MY_OBJECT, mObjectSL
                , mInfoResponse.getIdealObjectIds(), mInfoResponse.getIdealObjectLabelNames());
        showLabelData(DataType.MY_HOBBY, mHobbySL
                , mInfoResponse.getUniqueHobbyIds(), mInfoResponse.getUniqueHobbyLabelNames());
        if (TextUtils.isEmpty(mInfoResponse.getPersonSign())) {
            mSignSV.setRightHint(getString(R.string.no_special_sign_default));
        } else {
            mSignSV.setRightText(mInfoResponse.getPersonSign());
        }
        if (!TextUtils.isEmpty(mInfoResponse.getBirthday())) {
            mBirthdaySV.setRightText(mInfoResponse.getBirthday());
            mBirthdaySV.setRightTextTag(mInfoResponse.getBirthday());
        }
        if (!TextUtils.isEmpty(mInfoResponse.getCityId())) {
            mHomeSV.setRightText(mInfoResponse.getProvinceName() + " " + mInfoResponse.getCityName());
            mHomeSV.setRightTextTag(mInfoResponse.getProvinceId() + "," + mInfoResponse.getProvinceName()
                    + "," + mInfoResponse.getCityId() + "," + mInfoResponse.getCityName());
        }
        if (!TextUtils.isEmpty(mInfoResponse.getAlbum())) {
            mImagePaths.addAll(0, StringUtils.convertCommaStr2List(mInfoResponse.getAlbum()));
            mImageAdapter.notifyDataSetChanged();
            mAlbumHint.setText(getString(R.string.album_action_count_hint
                    , mImagePaths.size() - 1));
        }
        if (getIntent().getBooleanExtra("launchLabel", false)) {
            //进入标签选择
            mLabelSL.callOnClick();
        }
    }

    @Override
    protected void compressImageSuccess(File file) {
        mImageAdapter.notifyItemInserted(0);
        mAlbumHint.setText(getString(R.string.album_action_count_hint
                , mImagePaths.size() - 1));
        if (isImageCompressed()) {
            mRecyclerView.requestLayout();
            mImageAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void uploadImagesSuccess(final String imageUrls) {
        mRecyclerView.setTag(R.id.data_tag, null);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!isFinishing()) {
                    submitData(imageUrls);
                    replaceLoading(getString(R.string.submit_data_doing));
                }
            }
        });
    }

    /**
     * 标签列表转id串
     *
     * @param labelList
     * @return
     */
    private String convertLabelIds(List<LabelItem> labelList) {
        if (labelList == null) {
            return "";
        }
        StringBuilder strBuilder = new StringBuilder();
        for (LabelItem label : labelList) {
            strBuilder.append(label.getLabelId()).append(",");
        }
        if (strBuilder.lastIndexOf(",") > -1) {
            strBuilder.deleteCharAt(strBuilder.length() - 1);
        }
        return strBuilder.toString();
    }

    /**
     * 提交编辑数据
     *
     * @param imageUrls
     */
    private void submitData(String imageUrls) {
        EditInfoRequest request = new EditInfoRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setNickName(mNameSV.getRightText());
        request.setAlbum(imageUrls);
        request.setPersonSign(mSignSV.getRightText());
        request.setMyLabelIds(convertLabelIds((List<LabelItem>) mLabelSL.getRightTextTag()));
        request.setIdealObjectIds(convertLabelIds((List<LabelItem>) mObjectSL.getRightTextTag()));
        request.setUniqueHobbyIds(convertLabelIds((List<LabelItem>) mHobbySL.getRightTextTag()));
        if (mBirthdaySV.getRightTextTag() != null) {
            request.setBirthday(mBirthdaySV.getRightTextTag().toString());
        }
        if (mHomeSV.getRightTextTag() != null) {
            String[] homes = mHomeSV.getRightTextTag().toString().split(",");
            if (homes.length == 4) {
                request.setProvinceId(homes[0]);
                request.setProvinceName(homes[1]);
                request.setCityId(homes[2]);
                request.setCityName(homes[3]);
            }
        }
        OkRequest.getInstance().withUrl(UrlConfig.EDIT_INFO)
                .withRequest(request).doRequest(EditInfoRequest.class.getSimpleName(), new OkCallback<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response, String srcData) {
                dismissLoading();
                if (response.isSuccess()) {
                    Toasty.showNormal(R.string.submit_success);
                    EventBus.getDefault().post(new RefreshEvent(DataType.REFRESH_USER_INFO));
                    finish();
                } else {
                    Toasty.showNormal(response.getMessage());
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_right_title) {
            if (mLabelSL.getRightTextTag() == null) {
                Toasty.showNormal(R.string.my_label_empty);
                return;
            }
            if (mObjectSL.getRightTextTag() == null) {
                Toasty.showNormal(R.string.my_object_empty);
                return;
            }
            //提交
            if (mImagePaths.size() <= 1) {
                showLoading(R.string.submit_data_doing);
                submitData(null);
            } else {
                if (!isImageCompressed()) {
                    Toasty.showNormal(R.string.wait_for_image_compress);
                    return;
                }
                showLoading(R.string.upload_image_doing);
                List<String> uploadList = new ArrayList<>();
                uploadList.addAll(mImagePaths.subList(0, mImagePaths.size() - 1));
                mRecyclerView.setTag(R.id.data_tag, uploadList);
                OssManager.getInstance(ApUtils.getApp()).ossUpload(uploadList, new ArrayList<String>(), this);
            }
            return;
        }
        if (v == mNameSV) {
            //昵称
            SingleInputEvent inputEvent = new SingleInputEvent();
            inputEvent.type = 1;
            inputEvent.maxLength = 10;
            inputEvent.preResult = mNameSV.getRightText();
            inputEvent.title = mNameSV.getLeftText();
            inputEvent.titleHint = getString(R.string.nick_name_hint);
            SingleInputActivity.launchActivity(this, inputEvent);
            return;
        }
        if (v == mBirthdaySV) {
            //出生年月
            new DatePickerPopWin.Builder(this, new DatePickerPopWin.OnDatePickedListener() {
                @Override
                public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                    mBirthdaySV.setRightText(dateDesc);
                    mBirthdaySV.setRightTextTag(dateDesc);
                }
            }).minYear(1900)
                    .maxYear(2100)
                    .dateChose("1990-1-1")
                    .setWindowWidth(ScreenUtils.getScreenWidth() * 4 / 5)
                    .build(RcUser.getInstance().getSex()).showPopWin(this);
            return;
        }
        if (v == mHomeSV) {
            //家乡
            new ProvincePickPopWin(this, RcUser.getInstance().getSex(),
                    "440000", "440100", ScreenUtils.getScreenWidth() * 4 / 5
                    , null, new ProvincePickPopWin.OnAddressPickCompletedListener() {
                @Override
                public void onAddressPickCompleted(String province, String provinceId, String city, String cityId) {
                    mHomeSV.setRightText(province + " " + city);
                    mHomeSV.setRightTextTag(provinceId + "," + province + "," + cityId + "," + city);
                }
            }).showPopWin(this);
            return;
        }
        if (v.getId() == R.id.ssv_sign) {
            //个性签名
            SingleInputEvent inputEvent = new SingleInputEvent();
            inputEvent.type = 2;
            inputEvent.maxLength = 30;
            inputEvent.preResult = mSignSV.getRightText();
            inputEvent.title = getString(R.string.special_sign);
            inputEvent.titleHint = getString(R.string.special_sign_hint);
            SingleInputActivity.launchActivity(this, inputEvent);
            return;
        }
        if (v.getId() == R.id.ssl_my_label || v.getId() == R.id.ssl_my_object
                || v.getId() == R.id.ssl_my_hobby) {
            //三种标签
            List<LabelItem> labelList = new ArrayList<>();
            if (mLabelSL.getRightTextTag() != null) {
                labelList.addAll((Collection<? extends LabelItem>) mLabelSL.getRightTextTag());
            }
            if (mObjectSL.getRightTextTag() != null) {
                labelList.addAll((Collection<? extends LabelItem>) mObjectSL.getRightTextTag());
            }
            if (mHobbySL.getRightTextTag() != null) {
                labelList.addAll((Collection<? extends LabelItem>) mHobbySL.getRightTextTag());
            }
            SelectLabelsActivity.launchActivity(this, labelList);
            return;
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        mImageAdapter.remove(position);
        mRecyclerView.requestLayout();
        mAlbumHint.setText(getString(R.string.album_action_count_hint
                , mImagePaths.size() - 1));
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (position == mImagePaths.size() - 1) {
            KeyboardUtils.hideSoftInput(this);
            new MediaPopWindow(this, this).showPopWindow();
        } else if (position >= 0) {
            ArrayList<String> urls = new ArrayList<>(mImageAdapter.getData());
            urls.remove(urls.size() - 1);
            BrowserImageActivity.launchActivity(this, view, urls, position);
        }
    }

    /**
     * 显示标签项
     *
     * @param type
     * @param labelSL
     * @param idStr
     * @param nameStr
     */
    private void showLabelData(int type, SingleSelectView labelSL, String idStr, String nameStr) {
        if (TextUtils.isEmpty(idStr)) {
            return;
        }
        List<LabelItem> labelItemList = new ArrayList<>();
        String[] ids = idStr.split(",");
        String[] names = nameStr.split(",");
        for (int i = 0; i < ids.length; i++) {
            LabelItem labelItem = new LabelItem();
            labelItem.setType(type);
            labelItem.setLabelId(ids[i]);
            labelItem.setLabelName(names[i]);
            labelItemList.add(labelItem);

        }
        labelSL.setRightText(nameStr.replace(",", "、"));
        labelSL.setRightTextTag(labelItemList);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SingleInputEvent event) {
        if (event.type == 1) {
            //昵称
            mNameSV.setRightText(event.latestResult);
            return;
        }
        if (event.type == 2) {
            //个性签名
            mSignSV.setRightText(event.latestResult);
            return;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SelectedLabelEvent event) {
        List<LabelItem> labelList = new ArrayList<>();
        List<LabelItem> objectList = new ArrayList<>();
        List<LabelItem> hobbyList = new ArrayList<>();
        StringBuilder labelBuilder = new StringBuilder();
        StringBuilder objectBuilder = new StringBuilder();
        StringBuilder hobbyBuilder = new StringBuilder();
        for (LabelItem labelItem : event.selectedLabels) {
            if (labelItem.getType() == DataType.MY_LABEL) {
                labelList.add(labelItem);
                labelBuilder.append(labelItem.getLabelName()).append("、");
            } else if (labelItem.getType() == DataType.MY_OBJECT) {
                objectList.add(labelItem);
                objectBuilder.append(labelItem.getLabelName()).append("、");
            } else {
                hobbyList.add(labelItem);
                hobbyBuilder.append(labelItem.getLabelName()).append("、");
            }
        }
        if (labelBuilder.length() > 0) {
            labelBuilder.deleteCharAt(labelBuilder.length() - 1);
        }
        if (objectBuilder.length() > 0) {
            objectBuilder.deleteCharAt(objectBuilder.length() - 1);
        }
        if (hobbyBuilder.length() > 0) {
            hobbyBuilder.deleteCharAt(hobbyBuilder.length() - 1);
        }
        mLabelSL.setRightText(labelBuilder.toString());
        mLabelSL.setRightTextTag(labelList);
        mObjectSL.setRightText(objectBuilder.toString());
        mObjectSL.setRightTextTag(objectList);
        mHobbySL.setRightText(hobbyBuilder.toString());
        mHobbySL.setRightTextTag(hobbyList);
    }

    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            int exitPos = data.getIntExtra(BrowserImageActivity.IMG_CURRENT_POSITION, -1);
            TransitionViewHelper.onActivityReenter(this
                    , mImageAdapter.getViewByPosition(exitPos, R.id.iv_photo));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        OkRequest.getInstance().cancelTag(EditInfoActivity.class.getSimpleName());
        Object obj = mRecyclerView.getTag(R.id.data_tag);
        if (obj != null) {
            OssManager.getInstance(ApUtils.getApp())
                    .cancelAsyncTask(obj.toString());
        }
    }

}
